package com.hatricks.is.algorithm.abc;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC1 {

    private static final ReentrantLock LOCK = new ReentrantLock();
    private static final Condition condition1 = LOCK.newCondition();
    private static final Condition condition2 = LOCK.newCondition();
    private static final Condition condition3 = LOCK.newCondition();
    private static int state = 0;

    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintTask("a", condition1, condition2, 0));
        Thread threadB = new Thread(new PrintTask("b", condition2, condition3, 1));
        Thread threadC = new Thread(new PrintTask("c", condition3, condition1, 2));

        threadA.start();
        threadB.start();
        threadC.start();
    }

    static class PrintTask implements Runnable {
        private final String letter;
        private final Condition conditionCurrent;
        private final Condition conditionNext;
        private final int targetState;

        public PrintTask(String letter, Condition current, Condition next, int targetState) {
            this.letter = letter;
            this.conditionCurrent = current;
            this.conditionNext = next;
            this.targetState = targetState;
        }

        @SneakyThrows
        @Override
        public void run() {
            for (int i = 0; i < 10; ) {
                LOCK.lock();
                try {
                    if (state % 3 != targetState) {
                        conditionCurrent.await();
                    }
                    System.out.println(letter);
                    state++;
                    i++;
                    conditionNext.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    LOCK.unlock();
                }
            }
        }
    }
}
